package com.cskaoyan.service.wxorder;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.wxAuth.bo.WxAuthCommentBo;
import com.cskaoyan.bean.wxorder.bo.WxOrderSubmitBo;
import com.cskaoyan.bean.wxorder.vo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.BeanUtils;
import com.cskaoyan.utils.DateUtils;
import com.cskaoyan.weixin.bean.address.Address;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Service
public class WxOrderServiceImp implements WxOrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderGoodsMapper orderGoodsMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    GrouponRulesMapper grouponRulesMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    AddressMapper addressMapper;

    @Override
    public WxOrderListVo list(Integer showType, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        Subject subject = SecurityUtils.getSubject();
        User1 user = (User1) subject.getPrincipals().getPrimaryPrincipal();
        if (showType == null) {
            showType = 0;
        }
        List<WxOrderListData> wxOrderListDatas = orderMapper.selectWxOrderListDataByUserId(user.getId(), showType);
        for (WxOrderListData wxOrderListData : wxOrderListDatas) {
            Order order = orderMapper.selectByPrimaryKey(wxOrderListData.getId());
            BigDecimal grouponPrice = order.getGrouponPrice();
            if (grouponPrice.doubleValue() == 0.0) {
                wxOrderListData.setIsGroupin(false);
            }

            Short orderStatus = order.getOrderStatus();
            if (orderStatus == 101) {
                WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(true, true, true, false, false, false, true);
                wxOrderListData.setOrderStatusText("未付款");
                wxOrderListData.setHandleOption(wxOrderListDataHandleOption);
            }

            if (orderStatus == 102) {
                wxOrderListData.setOrderStatusText("用户取消");
                WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, true, false, false, false, false, true);
                wxOrderListData.setHandleOption(wxOrderListDataHandleOption);
            }
            if (orderStatus == 103) {
                wxOrderListData.setOrderStatusText("系统取消");
                WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, true, false, false, false, false, true);
                wxOrderListData.setHandleOption(wxOrderListDataHandleOption);
            }
            if (orderStatus == 201) {
                wxOrderListData.setOrderStatusText("已付款");
                WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, false, false, false, false, true, true);
                wxOrderListData.setHandleOption(wxOrderListDataHandleOption);
            }
            if (orderStatus == 202) {
                wxOrderListData.setOrderStatusText("申请退款");
                WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, false, true, false, false, true, true);
                wxOrderListData.setHandleOption(wxOrderListDataHandleOption);
            }if (orderStatus == 203) {
                wxOrderListData.setOrderStatusText("已退款");
                WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, true, true, false, false, true, true);
                wxOrderListData.setHandleOption(wxOrderListDataHandleOption);
            }if (orderStatus == 301) {
                wxOrderListData.setOrderStatusText("已发货");
                WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, false, false, false, true, true, true);
                wxOrderListData.setHandleOption(wxOrderListDataHandleOption);
            }
            if (orderStatus == 401) {

                wxOrderListData.setOrderStatusText("用户收货");
                WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, false, false, true, false, true, true);
                wxOrderListData.setHandleOption(wxOrderListDataHandleOption);
            }if (orderStatus == 402) {
                wxOrderListData.setOrderStatusText("系统收货");
                WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, false, false, true, false, true, true);
                wxOrderListData.setHandleOption(wxOrderListDataHandleOption);
            }
        }
        int size1 = wxOrderListDatas.size();
        WxOrderListVo wxOrderListVo = new WxOrderListVo();
        wxOrderListVo.setData(wxOrderListDatas);
        PageInfo<WxOrderListData> wxOrderListDataPageInfo = new PageInfo<>(wxOrderListDatas);
        long total = wxOrderListDataPageInfo.getTotal();
        wxOrderListVo.setCount(total);
        wxOrderListVo.setTotalPages(wxOrderListDataPageInfo.getPages());

        return wxOrderListVo;
    }

    @Override
    public WxOrderDetailVo getOrderDetail(Integer orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        WxOrderDetailOrderInfo orderInfo = orderMapper.selectWxOrderDetailOrderInfoById(orderId);
        Short orderStatus = order.getOrderStatus();
        if (orderStatus == 101) {
            WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(true, true, true, false, false, false, true);
            orderInfo.setOrderStatusText("未付款");
            orderInfo.setHandleOption(wxOrderListDataHandleOption);
        }

        if (orderStatus == 102) {
            orderInfo.setOrderStatusText("用户取消");
            WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, true, false, false, false, false, true);
            orderInfo.setHandleOption(wxOrderListDataHandleOption);
        }
        if (orderStatus == 103) {
            orderInfo.setOrderStatusText("系统取消");
            WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, true, false, false, false, false, true);
            orderInfo.setHandleOption(wxOrderListDataHandleOption);
        }
        if (orderStatus == 201) {
            orderInfo.setOrderStatusText("已付款");
            WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, false, false, false, false, true, true);
            orderInfo.setHandleOption(wxOrderListDataHandleOption);
        }
        if (orderStatus == 202) {
            orderInfo.setOrderStatusText("申请退款");
            WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, false, true, false, false, true, true);
            orderInfo.setHandleOption(wxOrderListDataHandleOption);
        }if (orderStatus == 203) {
            orderInfo.setOrderStatusText("已退款");
            WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, true, true, false, false, true, true);
            orderInfo.setHandleOption(wxOrderListDataHandleOption);
        }if (orderStatus == 301) {
            orderInfo.setOrderStatusText("已发货");
            WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, false, false, false, true, true, true);
            orderInfo.setHandleOption(wxOrderListDataHandleOption);
        }
        if (orderStatus == 401) {
            orderInfo.setOrderStatusText("用户收货");
            WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, false, false, true, false, true, true);
            orderInfo.setHandleOption(wxOrderListDataHandleOption);
        }if (orderStatus == 402) {
            orderInfo.setOrderStatusText("系统收货");
            WxOrderListDataHandleOption wxOrderListDataHandleOption = new WxOrderListDataHandleOption(false, false, false, true, false, true, true);
            orderInfo.setHandleOption(wxOrderListDataHandleOption);
        }
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        WxOrderDetailVo wxOrderDetailVo = new WxOrderDetailVo();
        wxOrderDetailVo.setOrderGoods(orderGoods);
        wxOrderDetailVo.setOrderInfo(orderInfo);
        return wxOrderDetailVo;
    }

    @Override
    public OrderGoods goods(Integer orderId, Integer goodsId) {
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        return orderGoods.get(0);
    }

    @Override
    public Integer addComment(WxAuthCommentBo commentPerm) {
        Integer orderGoodsId = commentPerm.getOrderGoodsId();
        Comment comment = new Comment();
        comment.setContent(commentPerm.getContent());
        if (commentPerm.getPicUrls() != null && !"".equals(commentPerm.getPicUrls()) ){
            comment.setPicUrls(commentPerm.getPicUrls());
            comment.setHasPicture(true);
        }else {
            comment.setHasPicture(false);
        }
        Integer orderId = commentPerm.getOrderGoodsId();
        Integer goodId = orderGoodsMapper.selectGoodIdByOrderId(orderId);
        comment.setValueId(goodId);
        Subject subject = SecurityUtils.getSubject();
        comment.setStar(commentPerm.getStar());
        User1 primaryPrincipal = (User1) subject.getPrincipals().getPrimaryPrincipal();
        comment.setUserId(primaryPrincipal.getId());
        Date dateTime = new Date();
        comment.setAddTime(dateTime);
        comment.setUpdateTime(dateTime);
        comment.setType((byte)3);
        Integer result = commentMapper.insertSelective(comment);
        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setId(orderGoodsId);
        orderGoods.setComment(comment.getId());
        Integer consequence = orderGoodsMapper.updateByPrimaryKeySelective(orderGoods);
        OrderGoods orderGoodsTrue = orderGoodsMapper.selectByPrimaryKey(orderGoodsId);
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        orderId = orderGoodsTrue.getOrderId();
        Order order1 = orderMapper.selectByPrimaryKey(orderId);
        Short comments = order1.getComments();
        Short trueComments = (short) (comments - 1);
        order1.setComments(trueComments);
        //order1.setEndTime(DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
        orderMapper.updateByPrimaryKeySelective(order1);
        criteria.andOrderIdEqualTo(orderGoodsTrue.getOrderId()).andDeletedEqualTo(false);
        return result == 1 && consequence == 1 ? 1 : 0;
    }

    @Override
    public Integer confirmForOrder(Integer orderId) {
        Order order = new Order();
        order.setId(orderId);
        order.setOrderStatus((short) 401);
        Date date = new Date();
        order.setConfirmTime(date);
        order.setUpdateTime(date);
        int result = orderMapper.updateByPrimaryKeySelective(order);
        return result;
    }

    @Override
    public Integer cancelOrderByOrderId(Integer orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setOrderStatus((short)102);
        Date currentDate = DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
        order.setUpdateTime(currentDate);
        order.setEndTime(currentDate);
        int result = orderMapper.updateByPrimaryKeySelective(order);
        return result;
    }

    @Override
    public Integer perpay(Integer oderId) {
        Order order = orderMapper.selectByPrimaryKey(oderId);
        order.setOrderStatus((short)201);
        order.setPayId("12138");
        Date currentDate = DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
        order.setUpdateTime(currentDate);
        order.setPayTime(currentDate);
        Integer result = orderMapper.updateByPrimaryKeySelective(order);
        return result;
    }

    @Override
    public Integer deleteOrderById(Integer oderId) {
        Order order = orderMapper.selectByPrimaryKey(oderId);
        order.setDeleted(true);
        Date currentDate = DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
        order.setUpdateTime(currentDate);
        order.setEndTime(currentDate);
        Integer result = orderMapper.updateByPrimaryKeySelective(order);
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(oderId).andDeletedEqualTo(false);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        for (OrderGoods orderGood : orderGoods) {
            orderGood.setDeleted(true);
            orderGoodsMapper.updateByPrimaryKeySelective(orderGood);
        }
        return result;
    }

    @Override
    public Integer refundOrderById(Integer oderId) {
        Order order = orderMapper.selectByPrimaryKey(oderId);
        order.setUpdateTime(DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
        order.setOrderStatus((short)202);
        Integer result = orderMapper.updateByPrimaryKeySelective(order);
        return result;
    }

    @Override
    public Integer addOrder(WxOrderSubmitBo submitPerm) {

        Integer couponId = submitPerm.getCouponId();
        Coupon coupon = couponMapper.selectByPrimaryKey(couponId);

        Subject subject = SecurityUtils.getSubject();
        User1 user = (User1) subject.getPrincipals().getPrimaryPrincipal();
        BigDecimal discount = new BigDecimal(0);
        if (coupon != null) {
            discount = coupon.getDiscount();
        }

        Address address = addressMapper.selectByPrimaryKey(submitPerm.getAddressId());
        Order order = new Order();
        Integer result = null;
        order.setUserId(user.getId());
        order.setOrderSn(DateUtils.getOrderSn());
        order.setOrderStatus((short)101);
        order.setConsignee(address.getName());
        order.setMobile(address.getMobile());
        order.setAddress(address.getAddress());
        order.setMessage(submitPerm.getMessage());
        order.setCouponPrice(discount);
        order.setIntegralPrice(new BigDecimal(0));
        order.setGrouponPrice(new BigDecimal(0));
        Integer cartId = submitPerm.getCartId();
        if (cartId != 0) {
            Cart cart = cartMapper.selectByPrimaryKey(cartId);
            BigDecimal goodsPrice = cart.getPrice().multiply(new BigDecimal(cart.getNumber()));
            updateOrderInSubmit(order, goodsPrice);
            order.setComments((short)1);
            result = orderMapper.insertSelective(order);
            OrderGoods orderGoods = BeanUtils.cartToOrderGoods(cart);
            orderGoods.setOrderId(order.getId());
            int i = orderGoodsMapper.insertSelective(orderGoods);
            cartMapper.deleteByPrimaryKey(cartId);
        }else {
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andUserIdEqualTo(user.getId());
            criteria.andCheckedEqualTo(true);
            List<Cart> carts = cartMapper.selectByExample(cartExample);
            BigDecimal goodsPrice = new BigDecimal(0);
            for (int i = 0; i < carts.size(); i++) {
                goodsPrice = goodsPrice.add(carts.get(i).getPrice());
            }
            updateOrderInSubmit(order, goodsPrice);
            order.setComments((short)carts.size());
            result = orderMapper.insertSelective(order);
            for (Cart cart : carts) {
                OrderGoods orderGoods = BeanUtils.cartToOrderGoods(cart);
                orderGoods.setOrderId(order.getId());
                orderGoodsMapper.insertSelective(orderGoods);
            }
            for (Cart cart : carts) {
                cartMapper.deleteByPrimaryKey(cart.getId());
            }
        }
        //Integer consequence = order.getId();

        return order.getId();
    }

    private void updateOrderInSubmit(Order order, BigDecimal goodsPrice) {
        order.setGoodsPrice(goodsPrice);
        if (goodsPrice.compareTo(new BigDecimal(88)) >= 0) {
            order.setFreightPrice(new BigDecimal(0));
            order.setOrderPrice(goodsPrice);
        } else {
            order.setFreightPrice(new BigDecimal(8));
            order.setOrderPrice(goodsPrice.add(new BigDecimal(8)));
        }
        order.setActualPrice(order.getOrderPrice().subtract(order.getCouponPrice()));
        Date currentDate = new Date();
        order.setAddTime(currentDate);
        order.setUpdateTime(currentDate);
        Date endTime = new Date(currentDate.getTime() + 30 * 60 * 1000);
        order.setEndTime(endTime);
    }
}
